package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.CustomerService;
import com.atguigu.jxc.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LogService logService;

    @Override
    public Map<String, Object> list(Integer page, Integer rows, String customerName) {

        page = page == 0 ? 1:page;
        int offset = (page -1)*rows;

        Map<String,Object> map = new HashMap<>();
        //分页
        List<Customer> customerList =  customerDao.selectList(offset,rows,customerName);
        //查找模糊查询的数量
        Integer count = customerDao.getCustomerCount(customerName);
        map.put("total",count);
        map.put("rows",customerList);
        logService.save(new Log(Log.SELECT_ACTION,"分页查询客户信息"));
        return map;
    }

    //保存或修改
    @Override
    public ServiceVO save(Customer customer) {
        //商户id是否存在
        if (customer.getCustomerId() == null){
            customerDao.saveCustomer(customer);
            logService.save(new Log(Log.INSERT_ACTION,"新增客户信息"));
        }
        //存在 更新
        customerDao.updateCustomer(customer);
        logService.save(new Log(Log.UPDATE_ACTION,"修改客户信息"));
        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }

    //删除
    @Override
    public ServiceVO delete(String ids) {
        String[] sid = ids.split(",");
        List<String> list = Arrays.asList(sid);
        for (String id : list) {
            logService.save(new Log(Log.DELETE_ACTION,"删除商户:"+customerDao.getCustomerById(Integer.parseInt(id)).getCustomerName()));
        }

        customerDao.delete(sid);
        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }


}
